package minefak3r;

/**
 *
 * @author Chriss & D4rky!
 */
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import static minefak3r.PackageManipulator.*;
import static minefak3r.Packages.*;

public class ClientReader extends Thread {

    DataInputStream dis;
    DataOutputStream dos;
    boolean sendData = true;

    public ClientReader(Socket client, Socket target) throws Exception {
        dis = new DataInputStream(client.getInputStream());
        dos = new DataOutputStream(target.getOutputStream());
    }

    @Override
    public void run() {
        try {
            while (true) {
                Thread.sleep(1);
                int bytes = dis.available();
                if (bytes > 0) {
                    byte packID = dis.readByte();
                    switch (packID) {
                        case PKG_PLAYER:
                            sendData = false;
                            handleOnGround(dis, dos);
                            break;
                        case PKG_PLAYERPOSITION:
                            sendData = false;
                            handlePosition(dis, dos);
                            break;
                        case PKG_PLAYERPOSLOOK:
                            sendData = false;
                            handlePositionLook(dis, dos);
                            break;
                        case PKG_PLAYERLOOK:
                            sendData = false;
                            handleLook(dis, dos);
                            break;
                    }
                    if (sendData) {
                        bytes = dis.available();
                        byte data[] = new byte[bytes];
                        dis.readFully(data);
                        dos.writeByte(packID);
                        dos.write(data);
                    }
                }
                sendData = true;
            }
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
    }
}
